/*
 * @lc app=leetcode.cn id=947 lang=typescript
 *
 * [947] 移除最多的同行或同列石头
 */

// @lc code=start

class UnionFind {
  parent: number[];
  size: number[];
  count: number;
  constructor(n: number = 0) {
    this.parent = new Array(n).fill(0).map((_, i) => i);
    this.size = new Array(n).fill(1);
    this.count = n;
  }
  find(x: number): number {
    return (this.parent[x] = this.parent[x] === x ? x : this.find(this.parent[x]));
  }
  union(x: number, y: number): void {
    let rx = this.find(x);
    let ry = this.find(y);
    if (rx === ry) return;
    if (this.size[rx] > this.size[ry]) {
      [rx, ry] = [ry, rx];
    }
    this.size[ry] += this.size[rx];
    this.parent[rx] = ry;
    this.count--;
  }
}

function removeStones(stones: number[][]): number {
  const size = stones.length;
  const unionFind = new UnionFind(size);
  // 记录石头的坐标
  const mapX = new Map();
  const mapY = new Map();

  for (let i = 0; i < size; i++) {
    let [x, y] = stones[i];
    // 当前行出现过，表示有石头，就连通
    if (mapX.has(x)) {
      unionFind.union(i, mapX.get(x));
    }
    // 当前列出现过，连通
    if (mapY.has(y)) {
      unionFind.union(i, mapY.get(y));
    }
    mapX.set(x, i);
    mapY.set(y, i);
  }
  // 石头的总数减去集合数就是答案
  return size - unionFind.count;
}
// @lc code=end
